package com.app.web.config.manager;

import com.app.utils.base.j2se.Logger;
import com.app.utils.base.j2se.StringHandler;
import com.app.utils.spring.ServerUrl;
import com.app.web.config.server.UrlServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: ys1->UrlManager
 * @Auther: 但何非
 * @Date: 2022/5/11 10:19
 * @Description:
 */
@Service
public class UrlManager implements Runnable{

    @Autowired
    private UrlServer urlServer;
    private static Map<String, ServerUrl> urlMap = new HashMap<>();
    @PostConstruct
    public void init () {
        new Thread(this).start();
    }
    @Override
    public void run() {
        while (true) {
            try {
                this.load();
                Thread.sleep(60*1000);
            } catch (Exception e) {
                Logger.error("UrlManager",  e);
            }
        }
    }

    private void load(){
        Logger.info("UrlManager---------------begin");
        List<ServerUrl>  list = urlServer.getUrl();
        if(StringHandler.isNotEmpty(list) && list.size()>0){
            Map<String,ServerUrl> maps = new HashMap<String,ServerUrl>();
            for (ServerUrl serverUrl : list){
                maps.put(serverUrl.url, serverUrl);
            }
            this.urlMap = maps;
        }
        Logger.info("UrlManager---------------end");
    }

    public static ServerUrl url(String uri){
        return urlMap.get(uri);
    }
}
